import React, { Component } from 'react';
import cx from 'classnames';

import View from 'lib/View.jsx';
import dispatcher from 'lib/dispatcher';
import ConditionItem from 'lib/components/ConditionItem.jsx';

export default class ConditionView extends Component {
  changeFieldHandler(index, item) {
    dispatcher.dispatch({
      $type: 'change_filter_field',
      index,
      item
    });
  } // changeFieldHandler

  changeFunctionHandler(index, item) {
    dispatcher.dispatch({
      $type: 'change_filter_func',
      index,
      item
    });
  } // changeFunctionHandler

  addFilterHandler() {
    dispatcher.dispatch({
      $type: 'add_filter'
    });
  } // addFilterHandler

  changeFilterRelationHandler() {
    dispatcher.dispatch({
      $type: 'change_filter_relation',
      relation: this.props.relation === 'and' ? 'or' : 'and'
    });
  } // changeFilterRelationHandler

  changeFilterHandler(index, filter) {
    dispatcher.dispatch({
      $type: 'change_filter_filter',
      index,
      filter
    });
  } // changeFilterHandler

  removeHandler(index) {
    dispatcher.dispatch({
      $type: 'remove_filter',
      index
    });
  } // removeHandler

  valueCompleteHandler(index) {
    dispatcher.dispatch({
      $type: 'complete_filter_value',
      index
    });
  } // valueCompleteHandler

  renderRelation() {
    return (
      <button
        className={ cx('filter-relation', {
          disabled: !this.props.relationEnabled || false
        })}
        type="button"
        onClick={ this.changeFilterRelationHandler.bind(this) }
        disabled={ !this.props.relationEnabled || false }>
        { this.props.relation === 'and' ? '且' : '或' }
      </button>
    );
  } // renderRelation

  render() {
    return (
      <div className="condition-body has-relation">
        {
          this.props.filters.length > 1 ? this.renderRelation() : null
        }
        {
          this.props.filters.map((item, index) => (
            <ConditionItem
              key={ index }
              { ...item }
              onFieldChanged={ this.changeFieldHandler.bind(this, index) }
              onFunctionChanged={ this.changeFunctionHandler.bind(this, index) }
              onFilterChanged={ this.changeFilterHandler.bind(this, index) }
              onRemoving={ this.removeHandler.bind(this, index) }
              onValueCompleted={ this.valueCompleteHandler.bind(this, index) }
              options={ this.props.options } />
          ), this)
        }
        <div className="iconfont creator" onClick={ this.addFilterHandler.bind(this) }>
          &#xe6bd;
        </div>
      </div>
    );
  } // render
}

ConditionView.defaultProps = {
  relation: 'and',
  relationEnabled: true,
  filters: [],
  options: []
}
